//
//  SYDownloadVedioWorking.m
//  PO_Chat
//
//  Created by -- on 2020/5/25.
//  Copyright © 2020 舒杨. All rights reserved.
//

#import "SYDownloadVedioWorking.h"

@interface SYDownloadVedioWorking () <NSURLSessionDelegate>

@property(nonatomic,strong)NSURLSessionDownloadTask *downloadTask;

/**总长度*/
@property(nonatomic,assign)NSInteger totalLength;

@property (nonatomic, copy) NSString *requestURL;


@end

@implementation SYDownloadVedioWorking

- (instancetype)initDownloadVedioWithUrl:(NSString*)requestURL {
    if (self == [super init]) {
        self.requestURL = requestURL;
        self.totalLength = 1;
        
        if (self.downloadTask) {
            self.downloadTask = nil;
        }
        
        NSURL *url = [NSURL URLWithString:self.requestURL];
        //创建管理类NSURLSessionConfiguration
        NSURLSessionConfiguration *config =[NSURLSessionConfiguration defaultSessionConfiguration];
        config.HTTPAdditionalHeaders =@{@"Accept-Encoding":@""};

        //初始化session并制定代理
        NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
        
        self.downloadTask = [session downloadTaskWithURL:url];
        // 开始
        [self.downloadTask resume];
    }
    return self;
}

#pragma mark NSSessionUrlDelegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    //下载进度
    double progress = totalBytesWritten / (double)totalBytesExpectedToWrite;
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.SYDownloadVedioProgressBlock) {
            self.SYDownloadVedioProgressBlock(progress);
        }
    });
}

//下载完成 保存到本地相册
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location {
    //1.拿到cache文件夹的路径
    NSString *cache=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    //2,拿到cache文件夹和文件名
    NSString *file=[cache stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    
    [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
    //3，保存视频到相册
    if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(file)) {
        //保存相册核心代码
        UISaveVideoAtPathToSavedPhotosAlbum(file, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
    }
}


//请求结束
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error {
    if (self.SYDownloadVedioCompleteBlock) {
        self.SYDownloadVedioCompleteBlock(error);
    }
}

- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSString *saveText = @"";
    BOOL isSave = NO;
    if (error) {
        saveText = [NSString stringWithFormat:@"保存视频失败%@", error.localizedDescription];
    }
    else {
        saveText = @"保存视频成功";
        isSave = YES;
    }
    if (self.SYDownloadVedioFinishSavingBlock) {
        self.SYDownloadVedioFinishSavingBlock(isSave, saveText);
    }
}

// 关闭下载
- (void)downLoadCancel {
    [self.downloadTask cancel];
}

@end
